package com.kakarote.hrm.task;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kakarote.core.utils.UserUtil;
import com.kakarote.hrm.entity.PO.HrmDataPushDetail;
import com.kakarote.hrm.entity.PO.HrmDataPushLog;
import com.kakarote.hrm.entity.VO.*;
import com.kakarote.hrm.constant.PushDataTypeEnum;
import com.kakarote.hrm.mapper.HrmDeptMapper;
import com.kakarote.hrm.mapper.HrmEmployeeMapper;
import com.kakarote.hrm.mapper.HrmPushDataDetailMapper;
import com.kakarote.hrm.mapper.HrmPushDataLogMapper;
import com.kakarote.hrm.service.IHrmDataPushLogService;
import com.kakarote.hrm.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author 92487
 * @Date 2024/3/13 20:31
 */

@Component
@EnableScheduling
@EnableAsync
@Slf4j
public class PushDataTask {

    @Value("${pushData.dept.get}")
    private String deptGetUrl;
    @Value("${pushData.dept.add}")
    private String deptAddUrl;
    @Value("${pushData.dept.update}")
    private String deptUpdateUrl;
    @Value("${pushData.dept.delete}")
    private String deptDeleteUrl;
    @Value("${pushData.employee.get}")
    private String empGetUrl;
    @Value("${pushData.employee.add}")
    private String empAddUrl;
    @Value("${pushData.employee.update}")
    private String empUpdateUrl;
    @Value("${pushData.employee.delete}")
    private String empDeleteUrl;

    @Autowired
    private HrmPushDataLogMapper pushDataLogMapper;
    @Autowired
    private IHrmDataPushLogService dataPushLogService;

    @Autowired
    private HrmDeptMapper deptMapper;
    @Autowired
    private HrmEmployeeMapper employeeMapper;

    @Autowired
    private HrmPushDataDetailMapper pushDataDetailMapper;

    @Scheduled(cron = "0 0 1 * * ? ")
    public void deptDataPushTask() {
        this.pushDept("定时任务数据推送");
    }

    public void pushDept(String remark) {
        log.info("开始部门同步数据");
        //同步日志详情
        List<HrmDataPushDetail> details = new ArrayList<>();
        //同步数据
        List<DeptDetailInforVO> addList = new ArrayList<>();
        List<DeptDetailInforVO> updateList = new ArrayList<>();
        List<String> deleteList = new ArrayList<>();
        //获取市政全部数据
        List<DeptResultVo> deptResultVos = new ArrayList<>();
        String resultStr = HttpUtils.createGetHttp(deptGetUrl, new HashMap<>());
        if (StrUtil.isNotEmpty(resultStr)) {
            JSONObject jsonObject = JSONObject.parseObject(resultStr);
            String text = jsonObject.getString("result");
            if (StrUtil.isNotEmpty(text)) {
                JSONArray jsonarray = JSONArray.parseArray(text);
                for (int n = 0; n < jsonarray.size(); n++) {
                    JSONObject json = jsonarray.getJSONObject(n);
                    DeptResultVo deptResultVo = JSON.parseObject(String.valueOf(json), DeptResultVo.class);
                    deptResultVos.add(deptResultVo);
                }
            }
        }
        Map<String, DeptResultVo> deptResultMap = new HashMap<>();
        if (!deptResultVos.isEmpty()) {
            deptResultMap = deptResultVos.stream().collect(Collectors.toMap(DeptResultVo::getDeptmentCode, v -> v));
        }
        log.info("市政部门deptResultMap数据：{}",JSON.toJSON(deptResultMap));
        //人资部门数据
        List<DeptDetailInforVO> deptDetails = deptMapper.selectPushDeptData(new ArrayList<>());
        Map<String, DeptDetailInforVO> deptDetailMap = new HashMap<>();
        if (!deptDetails.isEmpty()) {
            deptDetailMap = deptDetails.stream().collect(Collectors.toMap(DeptDetailInforVO::getDeptCode, v -> v));
        }
        log.info("人资部门数据获取成功");
        HashSet<String> deptCodeSet = new HashSet<>();
        deptCodeSet.addAll(deptResultMap.keySet());
        deptCodeSet.addAll(deptDetailMap.keySet());
        //数据对比
        for (String code : deptCodeSet) {
            if (deptDetailMap.containsKey(code) && !deptResultMap.containsKey(code)) {
                addList.add(deptDetailMap.get(code));
            } else if (!deptDetailMap.containsKey(code) && deptResultMap.containsKey(code)) {
                deleteList.add(code);
            } else {
                updateList.add(deptDetailMap.get(code));
            }
        }
        if (!addList.isEmpty()){
            addList = addList.stream().sorted(Comparator.comparing(DeptDetailInforVO::getLevel, Comparator.nullsLast(Integer::compare))).collect(Collectors.toList());
        }
        log.info("对比完成");
        //删除
        for (String code : deleteList) {
            Map<String, String> map = new HashMap();
            map.put("deptCode", code);
            String result = HttpUtils.createPostHttp(deptDeleteUrl, map);
            if (StrUtil.isNotEmpty(result)) {
                details.add(JSONObject.parseObject(result, HrmDataPushDetail.class));
            }
        }
        log.info("删除推送成功");
        //新增
        for (DeptDetailInforVO dept : addList) {
            Map<String, String> map = new HashMap();
            map.put("deptDetailInfor", JSON.toJSONString(dept));
            String result = HttpUtils.createPostHttp(deptAddUrl, map);
            if (StrUtil.isNotEmpty(result)) {
                details.add(JSONObject.parseObject(result, HrmDataPushDetail.class));
            }
        }
        log.info("新增推送成功");
        //修改
        for (DeptDetailInforVO dept : updateList) {
            Map<String, String> map = new HashMap();
            map.put("deptDetailInfor", JSON.toJSONString(dept));
            String result = HttpUtils.createPostHttp(deptUpdateUrl, map);
            if (StrUtil.isNotEmpty(result)) {
                details.add(JSONObject.parseObject(result, HrmDataPushDetail.class));
            }
        }
        log.info("修改推送成功");
        log.info("推送完成");
        //推送记录
        HrmDataPushLog l = new HrmDataPushLog();
        l.setType(PushDataTypeEnum.DEPT.getType());
        l.setRemark(remark);
        dataPushLogService.save(l);
        log.info("推送记录保存完成");
        //保存推送详情
        if (!details.isEmpty()) {
            for (HrmDataPushDetail detail : details) {
                detail.setPushId(l.getId());
                detail.setCreateUserId(UserUtil.getUserId());
            }
            pushDataDetailMapper.batchInsert(details);
        }
        log.info("推送详情保存完成");
    }

    @Scheduled(cron = "0 0 1 * * ? ")
    public void employeeDataPushTask() {
        this.pushEmployee("定时任务数据推送");
    }

    public void pushEmployee(String remark) {
        log.info("开始员工同步数据");
        //同步日志详情
        List<HrmDataPushDetail> details = new ArrayList<>();
        //同步数据
        List<UserDetailInfoVO> addList = new ArrayList<>();
        List<UserDetailInfoVO> updateList = new ArrayList<>();
        List<String> deleteList = new ArrayList<>();
        //获取市政全部数据
        List<EmployeeResultVo> empResultVos = new ArrayList<>();
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("currentPage","1");
        paramMap.put("pageSize","1");
        //总数
        int countNum = 0;
        String countStr = HttpUtils.createGetHttp(empGetUrl, paramMap);
        if (StrUtil.isNotEmpty(countStr)) {
            JSONObject jsonObject = JSONObject.parseObject(countStr);
            String text = jsonObject.getString("result");
            if (StrUtil.isNotEmpty(text)) {
                JSONObject listObj = JSONArray.parseObject(text);
                countNum = Integer.parseInt(listObj.get("countNum").toString());
            }
        }
        //获取市政全部数据
        final int batchSize = 1000;
        int remainder = countNum % batchSize;
        int resultNum = (remainder > 0) ? (countNum / batchSize + 1) : (countNum / batchSize);
        for (int i = 0; i < resultNum; i++) {
            paramMap.put("currentPage",String.valueOf(i+1));
            paramMap.put("pageSize", String.valueOf(batchSize));
            String resultStr = HttpUtils.createGetHttp(empGetUrl, paramMap);
            if (StrUtil.isNotEmpty(resultStr)) {
                JSONObject jsonObject = JSONObject.parseObject(resultStr);
                String text = jsonObject.getString("result");
                if (StrUtil.isNotEmpty(text)) {
                    JSONObject listObj = JSONArray.parseObject(text);
                    if (StrUtil.isNotEmpty(listObj.getString("list"))) {
                        JSONArray jsonarray = JSONArray.parseArray(listObj.getString("list"));
                        for (int n = 0; n < jsonarray.size(); n++) {
                            JSONObject json = jsonarray.getJSONObject(n);
                            EmployeeResultVo empResultVo = JSON.parseObject(String.valueOf(json), EmployeeResultVo.class);
                            empResultVos.add(empResultVo);
                        }
                    }
                }
            }
        }
        Map<String, EmployeeResultVo> empResultMap = new HashMap<>();
        if (!empResultVos.isEmpty()) {
            empResultMap = empResultVos.stream().collect(Collectors.toMap(EmployeeResultVo::getLoginname, v -> v));
        }
        log.info("市政人员empResultMap数据：{}",JSON.toJSON(empResultMap));
        //人资员工数据
        List<UserDetailInfoVO> empDetails = employeeMapper.selectPushEmployeeData(new ArrayList<>());
        Map<String, UserDetailInfoVO> empDetailMap = new HashMap<>();
        if (!empDetails.isEmpty()) {
            empDetailMap = empDetails.stream().collect(Collectors.toMap(UserDetailInfoVO::getLoginname, v -> v));
        }
        log.info("人资人员获取成功");
        HashSet<String> loginNameSet = new HashSet<>();
        loginNameSet.addAll(empResultMap.keySet());
        loginNameSet.addAll(empDetailMap.keySet());
        //数据对比
        for (String loginName : loginNameSet) {
            if (empDetailMap.containsKey(loginName) && !empResultMap.containsKey(loginName)) {
                addList.add(empDetailMap.get(loginName));
            } else if (!empDetailMap.containsKey(loginName) && empResultMap.containsKey(loginName)) {
                deleteList.add(loginName);
            } else {
                updateList.add(empDetailMap.get(loginName));
            }
        }
        log.info("对比完成");
        //删除
        for (String loginName : deleteList) {
            Map<String, String> map = new HashMap();
            map.put("loginName", loginName);
            String result = HttpUtils.createPostHttp(empDeleteUrl, map);
            if (StrUtil.isNotEmpty(result)) {
                details.add(JSONObject.parseObject(result, HrmDataPushDetail.class));
            }
        }
        log.info("删除推送成功");
        //新增
        for (UserDetailInfoVO emp : addList) {
            Map<String, String> map = new HashMap();
            map.put("userDetailInfo", JSON.toJSONString(emp));
            String result = HttpUtils.createPostHttp(empAddUrl, map);
            if (StrUtil.isNotEmpty(result)) {
                details.add(JSONObject.parseObject(result, HrmDataPushDetail.class));
            }
        }
        log.info("新增推送成功");
        //修改
        for (UserDetailInfoVO emp : updateList) {
            Map<String, String> map = new HashMap();
            map.put("userDetailInfo", JSON.toJSONString(emp));
            String result = HttpUtils.createPostHttp(empUpdateUrl, map);
            if (StrUtil.isNotEmpty(result)) {
                details.add(JSONObject.parseObject(result, HrmDataPushDetail.class));
            }
        }
        log.info("修改推送成功");
        //推送记录
        HrmDataPushLog  l= new HrmDataPushLog();
        l.setType(PushDataTypeEnum.EMPLOYEE.getType());
        l.setRemark(remark);
        dataPushLogService.save(l);
        log.info("推送记录保存完成");
        //保存推送详情
        if (!details.isEmpty()) {
            for (HrmDataPushDetail detail : details) {
                detail.setPushId(l.getId());
                detail.setCreateUserId(UserUtil.getUserId());
            }
            pushDataDetailMapper.batchInsert(details);
        }
        log.info("推送详情保存完成");
    }


}
